<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\AliSign;
use app\madmin\model\AliTemplate;
use app\madmin\model\SmsAliRecord;
use app\utils\AliSms;
use app\utils\TrimData;
use think\facade\Db;
use think\facade\Env;

class AliSmsService
{

    /**
     * @var AliSms
     */
    private $aliSms;

    /**
     * AliSmsService constructor.
     */
    public function __construct()
    {
        $this->aliSms = new AliSms();
    }

    /**
     * @param array $data
     * @param int $page
     * @param int $size
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAllRecord(array $data, int $page = 1, int $size = 10)
    {
        $admin = SmsAliRecord::field('id,phone,sign_name,template_code,biz_id,send_date,receive_date,status,create_time');
        $admin = TrimData::searchDataTrim($admin, $data, ['name', 'begin_date', 'end_date']);

        $list = $admin->where($data)->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * @param array $options
     * @return array
     */
    public function sendSms(array $options)
    {
        list($code, $data) = $this->aliSms->SendSms($options);
        if (HTTP_SUCCESS != $code)
            return [$code, $data];
        $phoneNumberList = explode(',', $options['PhoneNumbers']);
        $data = [];
        foreach ($phoneNumberList as $k => $v) {
            $data[$k]['phone'] = $v;
            $data[$k]['sign_name'] = $options['SignName'];
            $data[$k]['template_code'] = $options['TemplateCode'];
            $data[$k]['biz_id'] = $options['BizId'];
        }
        SmsAliRecord::insertAll($data);
        return [HTTP_SUCCESS, '已发送'];
    }

    /**
     * @param array $options
     * @return array
     */
    public function querySendDetails(array $options)
    {
        list($code, $data) = $this->aliSms->QuerySendDetails($options);
        if (HTTP_SUCCESS != $code)
            return [$code, $data];
        foreach ($data['SmsSendDetailDTOs'] as $v) {
            SmsAliRecord::update(
                [
                    'send_date' => $v['SendDate'],
                    'receive_date' => $data['ReceiveDate'],
                    'status' => $data['SendStatus']
                ],
                ['phone' => $options['PhoneNumber'], 'biz_id' => $options['BizId']]
            );
        }
        return [HTTP_SUCCESS, '查询成功，请更新'];
    }

}